import React, { lazy, Suspense } from 'react';
import { createBrowserRouter, Navigate } from 'react-router-dom';
import Layout from '@/components/Layout';
import PrivateRoute from '@/components/PrivateRoute';
import Login from '@/pages/Login';
import NotFound from '@/pages/NotFound';
import Forbidden from '@/pages/Forbidden';
import { componentMap } from './componentMap';

// 递归生成路由
const generateRoutes = (menus: any[]): any[] => {
  return menus.map(menu => {
    let element = null;
    if (menu.component && componentMap[menu.component]) {
      const Comp = componentMap[menu.component];
      element = (
        <PrivateRoute requiredPermissions={menu.permission ? [menu.permission] : []}>
          <Suspense fallback={<div>加载中...</div>}>
            <Comp />
          </Suspense>
        </PrivateRoute>
      );
    }
    return {
      path: menu.path, // 保持和后端一致
      element,
      children: menu.children ? generateRoutes(menu.children) : undefined,
    };
  });
};

// 获取menus
const menus = JSON.parse(localStorage.getItem('menus') || '[]');

export const router = createBrowserRouter([
  {
    path: '/',
    element: <Navigate to="/dashboard" replace />,
  },
  {
    path: '/login',
    element: <Login />,
  },
  {
    path: '/',
    element: (
      <PrivateRoute>
        <Layout />
      </PrivateRoute>
    ),
    children: [
      ...generateRoutes(menus),
      {
        path: '403',
        element: <Forbidden />,
      },
      {
        path: '*',
        element: <NotFound />,
      },
    ],
  },
]); 